import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Form, Input, Select, Row, Col, Tree, Button, Icon, Modal } from 'antd';
import ManageList from '@/components/ManageList';
import AdButton from '@/components/AdButton';
import DetailsInfo from './DetailsInfo';
import OperateInfo from './OperateInfo';
import { allDispatchType, codes } from './utils';
import styles from './index.less';

const { TreeNode } = Tree;
const { Search } = Input;
const { confirm, info } = Modal;

let gData = [];
let dataList = [];
const generateList = data => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const { id, partsName1, partsName2, partsName3, partsItems } = node;
    let text = `${partsName1}`;
    text = partsName2 ? `${text}/${partsName2}` : text;
    text = partsName3 ? `${text}/${partsName3}` : text;
    dataList.push({ key: id, title: text });
    if (partsItems) {
      generateList(partsItems);
    }
  }
};
const getParentKey = (key, tree) => {
  // console.log('key, tree', key, tree);
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.partsItems) {
      if (node.partsItems.some(item => item.id === key)) {
        parentKey = node.id;
      } else if (getParentKey(key, node.partsItems)) {
        parentKey = getParentKey(key, node.partsItems);
      }
    }
  }
  return parentKey;
};

@ManageList
@connect(({ PartsLib, menu }) => ({
  PartsLib,
  menuAuthority: menu.menuAuthority,
}))
@Form.create()
export default class PartsLibList extends Component {
  state = {
    handleType: 'add',
    globalListData: [],
    visible: false,
    visibleDetail: false,
    checkId: '',
    expandedKeys: [],
    searchValue: '',
    autoExpandParent: true,
  };
  className = 'PartsLibList';

  componentDidMount() {
    this.getPartsList();
  }

  //列表数据：
  getPartsList = (params = {}, type) => {
    const { dispatch } = this.props;
    const { expandedKeys } = this.state;
    dispatch({
      type: allDispatchType.list,
      payload: params,
      callback: res => {
        gData = res;
        generateList(gData);
        this.setState({
          globalListData: res,
          expandedKeys:
            res.length === 1 && expandedKeys.length === 0
              ? this.formatDefaultExpandKeys(res)
              : expandedKeys,
        });
      },
    });
  };

  formatDefaultExpandKeys = res => {
    let arr = [];
    let unit = {
      getIds: function(data) {
        data.map((item, i) => {
          arr.push(item.id);
          if (item.partsItems) {
            unit.getIds(item.partsItems);
          }
        });
      },
    };
    unit.getIds(res);
    return arr;
  };

  //展开收起树：
  onExpandTree = (expandedKey, { expanded: bool, node }) => {
    const { expandedKeys } = this.state;
    const id = node.props.eventKey;
    let arr = expandedKeys || [];
    if (bool) {
      arr = expandedKeys.filter(v => v !== id);
      arr.push(id);
    } else {
      arr = expandedKeys.filter(v => v !== id);
    }
    this.setState({
      expandedKeys: arr || [],
      autoExpandParent: false,
    });
  };

  //设置展开的树节点：
  setExpandedKeys = id => {
    const { expandedKeys } = this.state;
    expandedKeys.push(id);
    let arr = expandedKeys.filter(function(element, index, self) {
      return self && self.indexOf(element) === index;
    });
    this.setState({
      expandedKeys: arr || [],
    });
  };

  //搜索树节点：
  onChange = e => {
    const { value } = e.target;
    const expandedKeys = dataList
      .map(item => {
        const title = item.title;
        if (title && title.indexOf(value) > -1) {
          return getParentKey(item.key, gData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true,
    });
  };

  //选中的树节点：
  onSelectTree = (selectedKeys, info) => {
    const flag = this.getCode(codes.showDetail);
    if (!flag) return;
    const {
      selected,
      node: {
        props: { dataRef },
      },
    } = info;
    const { dispatch } = this.props;
    if (selected) {
      this.setState({
        visibleDetail: true,
        checkId: dataRef.id,
        handleType: 'edit',
      });
      let params = {};
      params.id = dataRef.id;
      dispatch({
        type: allDispatchType.detail,
        payload: params,
      });
      dispatch({
        type: allDispatchType.suppliersList,
        payload: params,
      });
    } else {
      this.setState({
        visibleDetail: false,
        selectedKeys: '',
        checkId: '',
      });
    }
  };

  //删除
  removeData = e => {
    const _this = this;
    const {
      dispatch,
      PartsLib: { partsDetails },
    } = this.props;
    const { checkId } = this.state;
    //有子节点禁止删除
    const detail = partsDetails[checkId];
    if (detail && detail.childAty > 0) {
      info({
        title: '温馨提示',
        okText: '确认',
        content: <div>该条数据有子节点，不能删除</div>,
      });
    } else {
      confirm({
        title: '确认删除这条数据吗?',
        content: '',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          dispatch({
            type: allDispatchType.remove,
            payload: { id: checkId },
            callback: res => {
              _this.setState({
                visibleDetail: false,
                checkId: '',
              });
              _this.getPartsList();
              _this.setExpandedKeys(checkId);
            },
          });
        },
      });
    }
  };

  //设置弹窗显隐
  setModalDetails = type => {
    const { visible } = this.state;
    this.setState({
      visible: !visible,
      handleType: 'edit',
    });
  };
  setModalOperate = type => {
    const { visible } = this.state;
    this.setState({
      visible: !visible,
    });
    // 1新增 0编辑
    if (type) {
      this.setState({
        handleType: 'add',
      });
    } else {
      this.setState({
        handleType: 'edit',
      });
    }
  };

  //导出：
  exportData = () => {
    console.log('导出');
  };

  //设置 state
  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  //判断详情权限：
  getCode = code => {
    const { menuAuthority } = this.props;
    let operateData = [];
    let newOperateData = [];
    menuAuthority.map(item => item.menuBODetail.map(item => operateData.push(item)));
    operateData.map(item => item.menuBODetail.map(item => newOperateData.push(item)));
    const newAuthority = newOperateData.filter(item => item.code === code);
    if (newAuthority.length > 0) {
      return true;
    }
    return false;
  };

  render() {
    const { form, menuAuthority } = this.props;
    const { getFieldDecorator } = form;
    const {
      visible,
      visibleDetail,
      globalListData,
      checkId,
      handleType,
      searchValue,
      expandedKeys,
      autoExpandParent,
    } = this.state;

    const InfoConParams = {
      id: checkId,
      handleType,
      getPartsList: this.getPartsList,
      setExpandedKeys: this.setExpandedKeys,
      setModalDetails: this.setModalDetails,
      removeData: this.removeData,
    };
    const InfoParams = {
      id: checkId,
      handleType,
      getPartsList: this.getPartsList,
      setExpandedKeys: this.setExpandedKeys,
      setModalOperate: this.setModalOperate,
    };
    let treeParams = {
      onSelect: this.onSelectTree,
      className: 'partsLib_treeBox',
      blockNode: true,
      onExpand: this.onExpandTree,
      expandedKeys,
      autoExpandParent,
    };

    const loop = data =>
      data.map(item => {
        let text = `${item.partsName1}`;
        text = item.partsName2 ? `${text}/${item.partsName2}` : text;
        text = item.partsName3 ? `${text}/${item.partsName3}` : text;

        const index = text ? text.indexOf(searchValue) : '';
        const beforeStr = text ? text.substr(0, index) : '';
        const afterStr = text ? text.substr(index + searchValue.length) : '';
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span style={{ color: '#f50' }}>{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{text}</span>
          );
        if (item.partsItems) {
          return (
            <TreeNode
              key={item.id}
              // title={<AdButton mode="a" text={title} code={codes.showDetail} />}
              title={title}
              dataRef={item}
              className="partsLib_treeNode"
            >
              {loop(item.partsItems)}
            </TreeNode>
          );
        }
        return (
          <TreeNode key={item.id} title={title} dataRef={item} className="partsLib_treeNode" />
        );
      });
    return (
      <Fragment>
        <Row gutter={24}>
          <Col className="gutter-row" span={8}>
            <div className={styles.gutterBox}>
              <div style={{ display: 'flex', justifyContent: 'flex-end', margin: '10px 10px 0 0' }}>
                <Button.Group>
                  {/* <AdButton
                    onClick={() => this.exportData()}
                    text="导出"
                    code={codes.export}
                  /> */}
                  <AdButton
                    onClick={() => this.setModalOperate(1)}
                    type="primary"
                    text="新增"
                    code={codes.add}
                  />
                </Button.Group>
              </div>
              {gData.length ? (
                <div>
                  <Search
                    style={{ width: '94%', margin: '10px 3% 0' }}
                    placeholder="请输入名称查询"
                    onChange={this.onChange}
                  />
                  <Tree showLine {...treeParams}>
                    {loop(gData)}
                  </Tree>
                </div>
              ) : (
                ''
              )}
            </div>
          </Col>
          <Col className="gutter-row" span={16}>
            {visibleDetail && <DetailsInfo {...InfoConParams} visible={visibleDetail} />}
          </Col>
        </Row>
        {visible && <OperateInfo {...InfoParams} visible={true} />}
      </Fragment>
    );
  }
}
